<template>
  <div class="description">
    <img :src="`${host}${book.image}`" />
    <div class="info">
      <h2>{{ book.name }}</h2>
      <div class="fs-lg">{{ book.author }}</div>
      <p>{{ book.description }}</p>
      <div class="fs-lg">
        库存: <span style="color: gray">{{ book.number }}</span>
      </div>
      <p class="fs-lg">
        单价: <span style="color: red">{{ book.price }}</span>
      </p>
      <p>
        <n-input-number
          v-model:value="num"
          style="width: 80px"
          min="1"
          :max="book.number"
          placeholder="0"
        />
      </p>
      <n-button @click="addHandle(book._id, num)" type="warning" size="large"
        >加入购物车</n-button
      >
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, Ref, toRefs, inject } from "vue";
import { NButton, NInputNumber, useMessage } from "naive-ui";

import { useBook } from "../hooks/UseBooks";
import { useCar } from "../hooks/UseCars";
import { Order } from "../interface/order.interface";

export default defineComponent({
  name: "Detail",
  components: {
    NButton,
    NInputNumber,
  },
  props: {
    id: {
      type: String,
      required: true,
    },
  },
  setup(props) {
    const num = ref(1);
    const { id } = toRefs(props);
    const { book, getBook } = useBook();
    const { addCar } = useCar();
    const host = ref(import.meta.env.VITE_SEREVER_HOST as string);
    const message = useMessage();

    getBook(id.value);

    const order = inject("order") as Ref<Order>;
    const flash = inject("flash") as Function;

    const addHandle = async (bookId: string, num: number) => {
      try {
        await addCar(bookId, num, order.value._id);
        message.success("添加成功");
      } catch (e) {
        message.error("请先登录");
      }
      flash();
    };

    return {
      num,
      book,
      host,
      getBook,
      addCar,
      addHandle,
    };
  },
});
</script>

<style lang="scss">
@import "../assets/styles/_variables.scss";

.description {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  padding: 5rem 0 2rem;

  img {
    padding: 0.2rem;
    margin-bottom: 3rem;
    border: 2px dashed map-get($colors, "gray");
  }

  .info {
    width: 60%;

    h2 {
      margin-top: 0;
    }
  }
}

@media screen and (max-width: 600px) {
  .description {
    padding: 3rem;

    img {
      width: 100%;
      margin-bottom: 3rem;
    }
    .info {
      width: 100%;
    }
  }
}
</style>
